package com.itheima.springbootwebtlias.service.Impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.springbootwebtlias.exception.DeletionIsNotAllowed;
import com.itheima.springbootwebtlias.mapper.ClazzMapper;
import com.itheima.springbootwebtlias.mapper.StudentMapper;
import com.itheima.springbootwebtlias.pojo.Clazz;
import com.itheima.springbootwebtlias.pojo.ClazzQueryParam;
import com.itheima.springbootwebtlias.pojo.PageResult;
import com.itheima.springbootwebtlias.service.ClazzService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class ClazzServiceImpl implements ClazzService {

    @Autowired
    private ClazzMapper clazzMapper;

    @Autowired
    private StudentMapper StudentMapper;

    //添加班级
    @Override
    public void saveClazz(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());

        clazzMapper.saveClazz(clazz);
    }

    //查询所有班级
    @Override
    public List<Clazz> selectAll() {
        List<Clazz> clazzs = clazzMapper.selectAll();

        //返回查询列表
        return clazzs;
    }

    @Override
    public PageResult page(ClazzQueryParam queryParam) {
       //1.使用分页插件实现分页查询
        //1.1启动分页插件
        PageHelper.startPage(queryParam.getPage(),queryParam.getPageSize());

        //1.2调用分页插件增强的持久层方法
        Page<Clazz> page = (Page<Clazz>)clazzMapper.selectByCondition(queryParam);

        //1.3 从分页插件增强方法的返回结果中，获取数据封装到PageResult对象中
        PageResult pageResult = new PageResult(page.getTotal(),page.getResult());

        return pageResult;
    }

    //删除班级
    @Override
    public void removeById(int id) {
        //0.判断班级是否关联有员工
        //1.如果存在学生，不允许删除
        Integer count = StudentMapper.selectByStudentId(id);
        if(count != 0){
            //不允许删除,存在学生
            throw new DeletionIsNotAllowed("当前班级存在员工，不允许删除");
        }
        clazzMapper.removeById(id);
    }

    //删除班级
    @Override
    public void removeById(Integer id) {
        //0.判断班级是否关联有员工
        //1.如果存在学生，不允许删除
        Integer count = StudentMapper.selectByStudentId(id);
        if(count != 0){
            //不允许删除,存在学生
            throw new DeletionIsNotAllowed("当前班级存在员工，不允许删除");
        }
        clazzMapper.removeById(id);
    }

    //根据id查询班级
    @Override
    public Clazz findById(int id) {
        return clazzMapper.findById(id);

    }

    //修改班级
    @Override
    public void update(Clazz clazz) {
        clazzMapper.update(clazz);
    }
}
